package stanford.com.balldating.chat.websocket;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import stanford.com.balldating.chat.model.UnReadMsg;
import stanford.com.balldating.chat.service.UnReadMsgService;

public class MyWebSocketHandler extends TextWebSocketHandler{
	
	public final static HashMap<String,WebSocketSession> users=new HashMap<String, WebSocketSession>();
	
	@Autowired
	private UnReadMsgService service;
	
	private WebSocketSession session;

	@Override
	public void afterConnectionEstablished(WebSocketSession session) throws Exception {
		// TODO Auto-generated method stub
		super.afterConnectionEstablished(session);
		
		this.session=session;
		
		String username=(String)session.getAttributes().get("username");
		
		if(username!=null&&!username.trim().equals("")){
		
			users.put(username, session);
			
			List<UnReadMsg> list=service.getUnReadMsg(username);
			
			for(UnReadMsg msg:list){
				JSONObject json=new JSONObject();
				json.put("to", msg.getToUser());
				json.put("from", msg.getFromUser());
				json.put("msg", msg.getMsg());
				session.sendMessage(new TextMessage(json.toString()));
			}
			
		}
	}
	
	@Override
	protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
		// TODO Auto-generated method stub
		super.handleTextMessage(session, message);
		
		String msg=new String(message.asBytes(),"utf-8");
		
		JSONObject object=new JSONObject(msg);
		
		String to=object.getString("to");
		
		sendMsg(to, message);
	}
	
	protected void sendMsg(String to,TextMessage message) throws JSONException, UnsupportedEncodingException {
		WebSocketSession session=users.get(to);
		if(session!=null&&session.isOpen()){
			try {
				session.sendMessage(message);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}else{
			UnReadMsg msg=new UnReadMsg();
			
			JSONObject object=new JSONObject(new String(message.asBytes(),"utf-8"));
			
			String m_to=object.getString("to");
			
			String m_from=object.getString("from");
			
			msg.setFromUser(m_from);
			msg.setToUser(m_to);
			msg.setMsg(object.getString("msg"));
			
			service.saveUnReadMsg(msg);
		}
	}
	
	
	@Override
	public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
		// TODO Auto-generated method stub
		super.afterConnectionClosed(session, status);
		
		String username=(String)session.getAttributes().get("username");
		
		if(username!=null&&!username.trim().equals("")){
			
			users.remove(username);
		}
	}
	
}
